package com.example.farmeri.ui.farm_manager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.example.farmeri.R;
import com.example.farmeri.adapter.MyItemDecoration;
import com.example.farmeri.adapter.FarmManagerRecycleViewAdapter;
import com.example.farmeri.data.DataParam;
import com.example.farmeri.data.RetrofitManager;
import com.example.farmeri.http.API;
import com.example.farmeri.pojo.vo.BaseCallBack;
import com.example.farmeri.presenter.farm_manager.FarmManagerPresenter;
import com.example.farmeri.presenter.farm_manager.IFarmManagerContract;
import com.example.farmeri.tools.KeyboardUtils;
import com.example.farmeri.tools.ResponseUtils;
import com.example.farmeri.ui.base.BaseLinearRecycleViewActivity;
import com.example.farmeri.ui.farm_manager.model.FarmManagerModel;
import com.example.farmeri.ui.farm_manager.model.ManagerModel;
import com.example.farmeri.ui.login.LoginActivity;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 农田管理
 */
public class FarmManagerActivity extends BaseLinearRecycleViewActivity<FarmManagerPresenter>
implements IFarmManagerContract {

    @BindView(R.id.farm_data_srl)
    SwipeRefreshLayout srl;

    @BindView(R.id.sheet_bottom_checkedNum)
    TextView checkedNum;

    @BindView(R.id.sheet_bottom_del_multi)
    Button multiDel;

    @BindView(R.id.farm_manager_main)
    ViewGroup mainLayout;    //主页面

    @BindView(R.id.farm_manager_search)
    ViewGroup searchLayout;    //搜索页

    @BindView(R.id.search_cancer)
    TextView searchCancer;    //取消搜索

    @BindView(R.id.search_edit)
    EditText searchEdit;    //搜索

    @BindView(R.id.search_recycle)
    RecyclerView searchRecycle;    //搜索结果

    @BindView(R.id.num_temperature)
    TextView numTemperature;    //温度数字

    @BindView(R.id.num_humidity)
    TextView numHumidity;    //湿度数字

    @BindView(R.id.num_sun)
    TextView numSun;    //湿度数字

    FarmManagerRecycleViewAdapter mAdapter;

    Integer selectIndex;    //列表中操作控件的位置
    String  selectId;
    List<String> temp_num = new LinkedList<>();
    FarmMangerService service = new FarmMangerServiceImpl();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_farm_manager);
        ButterKnife.bind(this);
        //EventBus.getDefault().register(this);
        init();

        getData();

        //批量删除
        multiDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从最大的开始删除
                Collections.sort(temp_num);
                for (int i=temp_num.size()-1;i>=0;i--){
                    Log.d("TAG", "onClick: position"+temp_num.get(i));
                    mAdapter.notifyItemRemoved(Integer.parseInt(temp_num.get(i)));
                }
                temp_num = new ArrayList<>();
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                checkedNum.setText("已勾选"+temp_num.size()+"个");
            }
        });

        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });

    }


    private Integer WHAT_ROLE = 0x102;
    private Integer WHAT_ALL_USERS = 0x103;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == WHAT_ALL_USERS){
                srl.setRefreshing(false);
                String json = JSON.toJSONString(msg.obj);
                List<ManagerModel> list = (List<ManagerModel>) JSON.parseArray(json, ManagerModel.class);
                initAdapter(list);
                if (isRefreshFrequently()){
                    reduceCredit(DataParam.getUserInfo().getId());
                }
            }else if(msg.what == WHAT_ROLE){
                String json = JSON.toJSONString(msg.obj);
                List<FarmManagerModel> list = JSON.parseArray(json,FarmManagerModel.class);
                list.forEach(model->{
                    if (model.getIdentity().equals("温度管理员")){
                        numTemperature.setText(model.getCount()+"人");
                    }else if (model.getIdentity().equals("湿度管理员")){
                        numHumidity.setText(model.getCount()+"人");
                    }else if (model.getIdentity().equals("光照管理员")){
                        numSun.setText(model.getCount()+"人");
                    }
                });
            }
        }
    };

    long time;
    /**
     * 是否频繁刷新
     * @return
     */
    private boolean isRefreshFrequently() {
        long now = System.currentTimeMillis();
        if (now - time < 5*1000){
            time = now;
            return true;
        }
        return false;
    }

    private void getData() {
        service.getRoleNumber(new BaseCallBack(handler,WHAT_ROLE));
        service.getSingleUserWithRole(new BaseCallBack(handler,WHAT_ALL_USERS));
    }

    private void init() {
        present = new FarmManagerPresenter(this);
        //设置ToolBar
        initToolBar(R.id.farm_manager_toolbar,"农田管理",true);
        //设置底部弹出框
        initBottomBehavior(R.id.sheet_bottom_container);
        //设置底部模态框
        initBottomSheetDialog(R.layout.dialog_model);
        //初始化搜索页面
        initSearchPager();
        //单条数据操作
        initSingleOperate();

    }

    /**
     * 初始化搜索页面
     */
    private void initSearchPager() {
        //搜索监听
        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    linearRecyclerViewAddData(R.id.search_recycle,
                            mAdapter,
                            MyItemDecoration.HIGH_LINE);
                    return true;
                }
                return false;
            }
        });

        //取消搜索
        searchCancer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchLayout.setVisibility(View.GONE);
                mainLayout.setVisibility(View.VISIBLE);
                searchRecycle.setAdapter(null);
                KeyboardUtils.hideKeyboard(searchEdit);
            }
        });
    }


    /**
     * 初始化Adapter
     * @param list
     */
    private void initAdapter(List<ManagerModel> list) {
        mAdapter = new FarmManagerRecycleViewAdapter(this,R.layout.item_farm_manager,getScreeWidth(),list);
        linearRecyclerViewAddData(R.id.farm_data_recycle_view,
                mAdapter,
                MyItemDecoration.HIGH_LINE);

        //为列表内的控件(锁定、删除等）设置监听
        mAdapter.setOnExtraClickListener(new FarmManagerRecycleViewAdapter.mOnExtraClickListener() {
            @Override
            public void onDelClick(View v, int position,String id) {
                bottomSheetDialog.show();
                selectIndex = position;
                selectId = id;
            }

            @Override
            public void onChecked(int position,String id) {
                if (temp_num.size() == 0){
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                temp_num.add(String.valueOf(position));
                checkedNum.setText("已勾选"+temp_num.size()+"个");
            }

            @Override
            public void onUnChecked(int position,String id) {
                temp_num.remove(String.valueOf(position));
                checkedNum.setText("已勾选"+temp_num.size()+"个");
                if (temp_num.size() == 0){
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
            }
        });

    }

    /**
     * 设置ToolBar内容
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        //添加操作按钮
        //MenuItem addAction = menu.add("添加");
        //addAction.setIcon(R.drawable.ic_add_white_24dp);
        //addAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        //addAction.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        //    @Override
        //    public boolean onMenuItemClick(MenuItem item) {
        //        Toast.makeText(FarmManagerActivity.this,"添加用户",Toast.LENGTH_SHORT).show();
        //        return true;
        //    }
        //});
        //添加搜索按钮
        MenuItem searchAction = menu.add("搜索");
        searchAction.setIcon(R.drawable.ic_search_white_24dp);
        searchAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        searchAction.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                mainLayout.setVisibility(View.GONE);
                searchLayout.setVisibility(View.VISIBLE);
                //设置输入内容为空
                searchEdit.setText("");
                //输入框获取焦点弹出软键盘
                KeyboardUtils.showKeyboard(searchEdit);
                return true;
            }
        });

        MenuItem addAction = menu.add("添加");
        addAction.setIcon(R.drawable.ic_add_white_24dp);
        addAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        addAction.setOnMenuItemClickListener(item -> {
            startActivity(new Intent(FarmManagerActivity.this,FarmManagerAddActivity.class));
            return true;
        });


        return super.onCreateOptionsMenu(menu);
    }

    TextView confirm;   //单选确定
    TextView cancer;    //单选返回
    protected void initSingleOperate() {
        //单选删除确定
        confirm = dialogView.findViewById(R.id.dialog_bottom_confirm);
        confirm.setOnClickListener(v -> {
            temp_num.remove(selectIndex);
            mAdapter.notifyItemRemoved(selectIndex);
            bottomSheetDialog.cancel();
            present.deleteFarmManager(selectId);
        });
        //单选删除取消
        cancer = dialogView.findViewById(R.id.dialog_bottom_cancer);
        cancer.setOnClickListener(v -> bottomSheetDialog.cancel());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }


    public void reduceCredit(String id) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();
        RetrofitManager.getManager().getRetrofit()
                .create(API.class)
                .reduceCredit(requestBody)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseUtils>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseUtils responseUtils) {
                        if(responseUtils.getCode() == 200){
                            DataParam.getUserInfo().setCredit(DataParam.getUserInfo().getCredit()-0.1f);
                            if (DataParam.getUserInfo().getCredit()<=0){
                                showToast("用户信誉值过低，已被锁定");
                                startActivity(new Intent(FarmManagerActivity.this, LoginActivity.class));
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showToast("更新信誉值失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void deleteFarmSuccess() {
        mAdapter.notify();
    }
}
